import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '../../assets/logo.png'
import './index.scss'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/modules/login'
import { useNavigate } from 'react-router-dom'

const Login = () => {
  const dispatch = useDispatch()
  const nav = useNavigate()
  /**
   * 表单校验通过后执行
   * @param {*} formData 表单变量的值
   */
  const onFinish = async (formData) => {
    // console.log('Success:', formData)
    //===========分发异步action=============

    try {
      await dispatch(loginAction(formData))
      message.success('登录成功')
      nav('/')
    } catch (error) {
      // console.log(error)
      message.error(error.response.data.message)
    }
  }
  // 校验选择框是否勾选
  /**
   *
   * @param {*} rule 校验规则
   * @param {*} value 校验表单项的值
   * 1.true选中
   * 2.false未选中
   */
  const validCode = (rule, value) => {
    if (!value) {
      return Promise.reject(new Error('请勾选用户协议！'))
    }
    return Promise.resolve()
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* ==========================登录表单=============================== */}
        {/* 校验触发时机 */}
        <Form
          validateTrigger={['onBlur', 'onChange']}
          //============================表单变量初始值==========================
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: false,
          }}
          onFinish={onFinish}
          autoComplete="off">
          {/* =========================第一个表单项 手机号=======================*/}
          <Form.Item
            //============name是定义表单变量名叫啥=>后台接口参数名保持一致===========
            name="mobile"
            //===========rules校验规则===========================================
            rules={[
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur',
              },
              { required: true, message: '请输入手机号' },
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>
          {/*===================================== 第二个表单项 验证码============*/}
          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              { required: true, message: '请输入验证码' },
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>
          {/* ===================================第三个表单项用户协议 ===============*/}
          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: validCode,
              },
            ]}>
            <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
          </Form.Item>
          {/* ===========================登录按钮  htmlType="submit"指定作为表单提交的按钮*/}
          <Form.Item>
            <Button size="large" type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
